package org.usmile.algorithms.learn.graph;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class AdjList implements Graph {
    private final int v;
    private final LinkedList<Integer>[] adj;

    private int e;


    @SuppressWarnings("unchecked")
    public AdjList(int v) {
        this.v = v;
        this.adj = new LinkedList[v];

        for (int i = 0; i < v; i++) {
            this.adj[i] = new LinkedList<>();
        }
    }

    @Override
    public int getV() {
        return this.v;
    }

    @Override
    public int getE() {
        return this.e;
    }

    @Override
    public void addEdge(int w, int v) {
        if (w == v || w >= this.v || v >= this.v) {
            return;
        }
        if (adj[w].contains(v)) {
            return;
        }

        adj[w].add(v);
        adj[v].add(w);

        e++;
    }

    @Override
    public boolean hasEdge(int w, int v) {
        if (w >= this.v || v >= this.v) {
            return false;
        }

        return adj[w].contains(v);
    }

    @Override
    public List<Integer> adj(int v) {
        if (v >= this.v) {
            return new ArrayList<>();
        }

        return adj[v];
    }

    @Override
    public int degree(int v) {
        return adj(v).size();
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(String.format("顶点数 = %d，边数 = %d \n", v, e));
        for (int v = 0; v < this.v; v++) {
            sb.append(v).append(": ");
            for (int w : adj[v]) {
                sb.append(w).append(" ");
            }
            sb.append("\n");
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        AdjList adjList = new AdjList(8);
        adjList.addEdge(0, 1);
        adjList.addEdge(1, 2);
        adjList.addEdge(3, 2);
        System.out.println(adjList.adj(1));
        System.out.println(adjList);
    }
}